<template>
  <a-tree-select :disabled='disabled' :dropdownStyle="{ maxHeight: '320px', maxWidth: '400px'}" :treeData="treeData"
                 :treeCheckStrictly="true" allowClear @change="onChange"
                 :loadData="onLoadData"
                 :getPopupContainer="node => node.parentNode"
                 :treeDefaultExpandAll='treeDefaultExpandAll' :value="selected"
                 :treeCheckable='treeCheckable' treeNodeFilterProp='label' />
</template>

<script>
import { getdepartment } from '@/api/createjobs'
import { getDepartmentLazyChildren } from '@/api/userManagement'
const treeData = [
  {
    label: '全部',
    key: '0',
    children: [],
    department: []
  }
]
let timeoutId = null // 倒计时id
// let tempKey = null
export default {
  props: [ 'treeCheckable', 'defaultValues', 'disabled' ],
  data () {
    return {
      treeData,
      selected: [],
      trees: [],
      treeDefaultExpandAll: false
    }
  },
  watch: {
    defaultValues: {
      handler (newValue) {
        if (newValue) {
          this.selected = []
          newValue.forEach(ele => {
            if (ele.id) {
              this.selected.push({ value: ele.id, label: ele.name })
            } else {
              this.selected.push(ele)
            }
          })
        }
      },
      immediate: true
    }
  },
  mounted () {
    this.initDepartment()
  },
  methods: {
    // filterChild (arry, key) {
    //   arry.some(item => {
    //     if (item.key === key) {
    //       tempKey = item
    //       return true
    //     } else if (item.children && item.children.length > 0) {
    //       this.filterChild(item.children, key)
    //     }
    //   })
    // },
    filterListData (arr, flag) {
      if (arr.children && arr.children.length > 0) {
        let arrTmp = [arr, ...arr.children]
        arrTmp.forEach(values => {
          // 将数组中所有数据push到一个array中
          if (!flag) {
            // 遍历this.selected，获取下标，删除数据
            this.selected.some((item, index) => item.value === values.value && this.selected.splice(index, 1))
          } else {
            if (this.selected.every(item => item.value !== values.value)) {
              this.selected.push({ value: values.value, label: values.label })
            }
          }
        // arr.children && arr.children.forEach(item => {
        //   this.filterListData(item, flag)
        // })
        })
      }
    },
    async onChange (value, unuse, info) {
      if (timeoutId) {
        clearTimeout(timeoutId)
        timeoutId = null
        // 双击
        // 通过node获取点击的数据
        // let currentKey = info.triggerValue
        // 根据子节点加载出所有节点
        if (this.onLoadData) {
          await this.onLoadData()
        }
        // 根据选中id对当前及子节点进行筛选treeData
        // this.filterChild(this.treeData, currentKey)
        // 判断为选中状态
        // 判定为取消状态
        this.filterListData(info.triggerNode.dataRef, info.checked)
        this.$emit('change', this.selected)
      } else {
        timeoutId = setTimeout(() => {
          timeoutId = null
          this.$emit('change', value)
        }, 300)
      }
    },
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        getDepartmentLazyChildren({
          id: treeNode.dataRef.id
        }).then(res => {
          if (res.code === 200) {
            const data = res.data
            treeNode.dataRef.children = data.map((item, index) => {
              return {
                label: item.name,
                value: item.id,
                key: item.id,
                id: item.id,
                isLeaf: !item.childrenFlag
              }
            })
          }
          this.treeData = [...this.treeData]
          resolve()
        })
      })
    },
    // 初始化
    initDepartment () {
      getdepartment().then(response => {
        if (response.data && response.data[0].hasOwnProperty('childrenFlag')) {
          this.treeData = response.data.map((item, index) => {
            return { label: item.name, value: item.id, key: item.id, id: item.id, isLeaf: !item.childrenFlag }
          })
        } else {
          this.onLoadData = null // onLoadData会一直执行
          this.treeDefaultExpandAll = true
          this.treeData = resizeTree(response.data)
          this.trees = response.data
        }
      }).catch(error => {
        return error.data
      })
    }
  }
}
function resizeTree (arr) {
  if (!Array.isArray(arr)) return
  return arr.map((item) => {
    return { label: item.name, value: item.id, key: item.id, children: resizeTree(item.children) }
  })
}
</script>
